package com.ytjj.qmyx.admin.service.imService.impl;

import com.alibaba.fastjson.JSON;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.im.ImRedisKeyConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.admin.eunm.im.ImSessionTransferTypeEnums;
import com.ytjj.qmyx.admin.mapper.AdminMapper;
import com.ytjj.qmyx.admin.mapper.ImMessageInfoMapper;
import com.ytjj.qmyx.admin.mapper.ImSessionTransInfoMapper;
import com.ytjj.qmyx.admin.model.ImMessageInfo;
import com.ytjj.qmyx.admin.model.ImSessionInfo;
import com.ytjj.qmyx.admin.model.ImSessionTransInfo;
import com.ytjj.qmyx.admin.model.request.im.ImSessionTransferRequest;
import com.ytjj.qmyx.admin.service.imService.ImSessionInfoService;
import com.ytjj.qmyx.admin.service.imService.ImSessionTransInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ImSessionTransInfoServiceImpl implements ImSessionTransInfoService {

    @Resource
    private ImSessionTransInfoMapper imSessionTransInfoMapper;
    @Autowired
    private ImSessionInfoService imSessionInfoService;
    @Autowired
    private RedisService redisService;
    @Resource
    private ImMessageInfoMapper imMessageInfoMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 会话转移
     * @param request
     * @return
     */
    @Transactional
    @Override
    public CommonResult doTrans(ImSessionTransferRequest request) {
        ImSessionInfo oldSessionInfo = imSessionInfoService.selectById(request.getSessionId());
        if (null == oldSessionInfo) {
            throw new ApiException("找不到会话信息");
        }
        oldSessionInfo.setServiceId(request.getTargetUserId());
//        CommonResult result = imSessionInfoService.sessionTransfer(request.getSessionId(), request.getTargetUserId());
        CommonResult result = imSessionInfoService.sessionTransferByOldObj(oldSessionInfo);
        if (ResultCode.SUCCESS.getCode()!= result.getCode()) {
            return result;
        }
        ImSessionTransInfo imSessionTransInfo = new ImSessionTransInfo();
        imSessionTransInfo.setSessionId(request.getSessionId());
        imSessionTransInfo.setOldServiceId(request.getSourceUserId());
        imSessionTransInfo.setNewServiceId(request.getTargetUserId());
        imSessionTransInfo.setType(ImSessionTransferTypeEnums.ACTIVE.getCode().byteValue());
        imSessionTransInfo.setCreateTime(new Date());
        imSessionTransInfo.setRemark(request.getRemak());

        int count = imSessionTransInfoMapper.insertSelective(imSessionTransInfo);
        if (count > 0) {
            try {
                redisService.set(ImRedisKeyConstant.IM_MEDIUMS_CUSTOMER + oldSessionInfo.getCustomerId(), request.getTargetUserId());//转移客户和客服的绑定关系
                redisService.set(ImRedisKeyConstant.CUSTOMER_BIND_SERVICE + oldSessionInfo.getCustomerId(), request.getTargetUserId());//客户绑定的客服
            } catch (Exception e) {
                log.error("===客服下线时存储转接信息异常==={}", e);
            }
            //在该会话中插入一条转接数据
            insertDoTransMessage(request);
            //转接后该会话的聊天记录改为已读
            imMessageInfoMapper.updateMessageStatusIsRead(request.getSessionId());

            try {
                log.info("===会话转移发送mq开始===");
                Map<String, String> mq_message = new HashMap<>();
                mq_message.put("receiveUserId", imSessionTransInfo.getNewServiceId());
                mq_message.put("sessionId", String.valueOf(request.getSessionId()));
                mq_message.put("type",QueueConstants.IM_TRANS_QUEUE);
//                rabbitTemplate.convertAndSend(QueueConstants.IM_TRANS_QUEUE, mq_message);
                stringRedisTemplate.convertAndSend(QueueConstants.IM_ADMIN_NOTIFY, JSON.toJSONString(mq_message));
                log.info("===会话转移发送mq成功===");
            } catch (Exception e) {
                log.error("===会话转移发送mq异常==={}", e);
            }
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    public void insertDoTransMessage(ImSessionTransferRequest request) {
        //根据email查询真实姓名
        String sourceUserName = adminMapper.selectByEmail(request.getSourceUserId());
        String targetUserName = adminMapper.selectByEmail(request.getTargetUserId());
        //在该会话中插入一条转接数据
        ImMessageInfo messageInfo = new ImMessageInfo();
        messageInfo.setSessionId(request.getSessionId());
        messageInfo.setSendUserId("0");
        messageInfo.setReceiveUserId("0");
        messageInfo.setMessageType((byte) 8);
        messageInfo.setContent(sourceUserName + "转接给" + targetUserName + ", 原因: " + (StringUtils.isEmpty(request.getRemak()) ? "暂无":request.getRemak()));
        messageInfo.setCreateTime(new Date());
        imMessageInfoMapper.insertSelective(messageInfo);
    }
}
